package cn.mntool.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * describe: 自定义回调方法实现
 *
 * @author lianying
 * @date 2020/07/25
 */
public class MyCustomWatcher implements Watcher {
    private ZooKeeper zooKeeper;
    private Stat stat=new Stat();

    public void setZooKeeper(ZooKeeper zooKeeper){
        this.zooKeeper=zooKeeper;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            //zk连接成功通知事件
            if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {  //zk目录节点数据变化通知事件
                try {
                    System.out.println("配置已修改，新值为：" + new String(this.zooKeeper.getData(watchedEvent.getPath(), false, stat)));
                    System.out.println("记录信息:\n"+stat.toString());
                    zooKeeper.exists(watchedEvent.getPath(),this);
                } catch (Exception e) {
                }
            }
        }
    }
}
